<?php
require("menuBarHead.php");
require("db_manage/dbFunctions.php");

$dbh = connectDB();
$resource_name = $_POST['select'];

if( strcmp($resource_name, "Rooms") == 0 )
	$subquery = "SELECT qr_code FROM Room";
else
	$subquery = "SELECT qr_code FROM Equipment WHERE equipment_name=:type";

$query = "SELECT rd_id,qr_code,requestor_id,projected_checkin FROM Resource_Designation WHERE qr_code = ANY( $subquery ) AND has_been_checked_in=0";

$stmt = $dbh->prepare($query);
$stmt->bindParam(':type',$resource_name);
$stmt->execute();

$checked_out_qr_codes = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($checked_out_qr_codes as $qr)
{
	if( strcmp($resource_name,"Rooms") == 0 )
		$table = "Room";
	else
		$table = "Equipment";
	
	$req_details_query = "SELECT * FROM Requestors WHERE req_id=:rid";
	$resource_details_query = "SELECT * FROM $table WHERE qr_code=:qr";

	$stmt = $dbh->prepare($req_details_query);
	$stmt->bindParam(':rid',$qr['requestor_id']);
	$stmt->execute();
		
	$req_details = $stmt->fetch(PDO::FETCH_ASSOC);
	$req_name = $req_details['first_name'] . " " . $req_details['last_name'];
	$req_email = $req_details['email'];

	$stmt = $dbh->prepare($resource_details_query);
	$stmt->bindParam(':qr',$qr['qr_code']);
	$stmt->execute();

	if( $stmt->rowCount() == 1 )
		$displayRows[] = array($stmt->fetch(PDO::FETCH_ASSOC),$qr['projected_checkin'],$req_name,$req_email);
}

if( strcmp($resource_name,"Rooms") == 0 )
	printRoomFormat($displayRows);
else
	printEquipmentFormat($displayRows, $resource_name);

require("menuBarClose.php");





function printRoomFormat($displayRows)
{
	print("<h2>Rooms Currently Checked Out</h2>");
	print("<table border=1>".
		"<tr><th>QR Code</th>".
		"<th>Building</th>".
		"<th>Floor</th>".
		"<th>Room Number</th>".
		"<th>Room Type</th>".
		"<th>Projected Checkin</th>".
		"<th>Requestor With Room</th>".
		"<th>Requestor Email</th></tr>");
	foreach( $displayRows as $r )
	{
		print("<tr><td>".$r[0]['qr_code']."</td>".
			"<td>".$r[0]['building']."</td>".
			"<td>".$r[0]['floor']."</td>".
			"<td>".$r[0]['room_number']."</td>".
			"<td>".$r[0]['room_type']."</td>".
			"<td>".$r[1]."</td>".
			"<td>".$r[2]."</td>".
			"<td>".$r[3]."</td></tr>\n");
	}
	print("</table>");

}

function printEquipmentFormat($displayRows, $equipName)
{
	
	print("<h2>".$equipName."(s) Currently Checked Out</h2>");
	print("<table border=1>".
		"<tr><th>QR Code</th>".
		"<th>Equipment Name</th>".
		"<th>Serial Number</th>".
		"<th>Current Condition</th>".
		"<th>Projected Checkin</th>".
		"<th>Requestor With Equipment</th>".
		"<th>Requestor Email</th></tr>");
	foreach( $displayRows as $e )
	{
		print("<tr><td>".$e[0]['qr_code']."</td>".
			"<td>".$e[0]['equipment_name']."</td>".
			"<td>".$e[0]['serial_number']."</td>".
			"<td>".$e[0]['current_condition']."</td>".
			"<td>".$e[1]."</td>".
			"<td>".$e[2]."</td>".
			"<td>".$e[3]."</td></tr>\n");
	}
	print("</table>");
}
?>
